package com.demo.utils;

import com.demo.dto.UserDetailDto;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class JwtUtils {
    //签名的密钥
    public static final String ENCODE_CODE_KEY = "mySecret";
    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";

    /**
     * 加密信息
     *
     * @param id            标志ID号，JWT的唯一标志，根据业务需要设置已给不重复的值即可，后面生成一次性token,尽量使用【UUID类生成随机字符串】
     * @param subject       JWT的标志主体，拥有者，一般用用户信息的用户名
     * @param userDetailDto 用户详情信息 只对用户ID号、用户名、用户密码封装加密程Token
     * @param expire        token过期时间 单位秒
     * @return String
     */
    public String createToken(String id, String subject, UserDetailDto userDetailDto, long expire) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", userDetailDto.getId());
        claims.put("username", userDetailDto.getUsername());
        claims.put("password", userDetailDto.getPassword());
        Date date = new Date();
        JwtBuilder jwtBuilder = Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setId(id)
                .setIssuedAt(date)
                .setExpiration(new Date(System.currentTimeMillis() + expire * 1000))
                .signWith(SignatureAlgorithm.HS256, ENCODE_CODE_KEY);//mySecret为：密钥

        return jwtBuilder.compact();
    }

    /**
     * 解密Token
     *
     * @param token
     * @return
     * @throws Exception
     */
    public Claims getClaimsFromToken(String token) throws Exception {
        Claims claims = Jwts.parser().setSigningKey(ENCODE_CODE_KEY).parseClaimsJws(token).getBody();
        return claims;
    }

    /**
     * 通过Token获取用户ID号 后面两个方法类似
     *
     * @param token
     * @return
     * @throws Exception
     */
    public long getIDFromToken(String token) throws Exception {
        Claims claims = getClaimsFromToken(token);
        return (long) claims.get("id");
    }

    public String getUsernameFromToken(String token) throws Exception {
        Claims claims = getClaimsFromToken(token);
        return (String) claims.get("username");
    }

    public String getPasswordFromToken(String token) throws Exception {
        Claims claims = getClaimsFromToken(token);
        return (String) claims.get("password");
    }

    /**
     * 测试
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        UserDetailDto userDetailDto = new UserDetailDto();
        userDetailDto.setId(1);
        userDetailDto.setUsername("admin");
        userDetailDto.setPassword("123123");
        JwtUtils jwtUtils = new JwtUtils();
        //8acdc688-40fc-4bef-91f4-bc57ece25b38
        String string2 = UUID.randomUUID().toString();
        String string = jwtUtils.createToken(string2, userDetailDto.getUsername(), userDetailDto, 3600);
        System.out.println(string);
        System.out.println("====================解密测试===========================");
        Claims claims = jwtUtils.getClaimsFromToken(string);
    }


}
